package com.example.springtxjta.service;

import com.example.springtxjta.dao.CustomerRepository;
import com.example.springtxjta.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class CustomerServiceInCode {

    private final CustomerRepository customerRepository;
    private final PlatformTransactionManager platformTransactionManager;

    @Autowired
    public CustomerServiceInCode(CustomerRepository customerRepository, PlatformTransactionManager platformTransactionManager) {
        this.customerRepository = customerRepository;
        this.platformTransactionManager = platformTransactionManager;
    }

    public Customer create(Customer customer) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus ts = platformTransactionManager.getTransaction(def);
        try {
            customerRepository.save(customer);
            platformTransactionManager.commit(ts);
            return customer;
        } catch (Exception e) {
            platformTransactionManager.rollback(ts);
            throw e;
        }
    }

}
